<?php
/**
 * Created by PhpStorm.
 * User: lwt
 * Date: 2018/12/28
 * Time: 16:35
 */

namespace app\api\controller\books;



class Pdf extends Base
{
  private $_speed = 1024;   // 下载速度

  public static $rule = [
    'getList' => [

    ],
  ];

  /**
   * @param string username * 用户名
   * @return object RespondVo 封装对象
   * @api 查询接口
   * @type post
   * @desc getList
   */
  public function getList()
  {
    try {
      $pagesize = 20;
      $sql = db("pdf pdf");
      if (isset($this->params["title"]) && !empty($this->params["title"])) {
        $sql->whereLike('pdf.name', '%' . $this->params["title"] . '%');
      }
      $countsql = clone $sql;
      $count = $countsql->count();
      $total = $count % $pagesize == 0 ? intval($count / $pagesize) : intval($count / $pagesize + 1);
      $list = $sql->page($this->params['page'].','.$pagesize)->order("pdf.id asc")->select();
      return $this->return_msg(200, '查询', ['total'=>$total, 'array'=>$list]);
    } catch (\Exception $e) {
//      $this->db_api_log($e->getMessage(), $e->getTraceAsString(), $this->ERROR);
      $this->return_msg(400, $e->getMessage());
    }
  }

  /** 下载
   * @param String  $file   要下载的文件路径
   * @param String  $name   文件名称,为空则与下载的文件名称一样
   * @param boolean $reload 是否开启断点续传
   */
  public function download($file, $name='', $reload=false){
//    $file = "/Users/lwt/Documents/github_pdf/linear_pdf/王海：滴滴移动端基础架构的演进与探索.pdf";
    $file = "/Users/lwt/Documents/github_pdf/PHP应用程序安全编程.pdf";
    $fname = 'redis设计与实现(第二版)优化.pdf';
    $fhandle = fopen($file, 'rb');//文件句柄
    $fsize = filesize($file);//文件大小

    //断点续传和整个文件下载的判断，支持多段下载
    if (!empty($_SERVER['HTTP_RANGE'])) {
      $range = str_replace("=", "-", $_SERVER['HTTP_RANGE']);
      $match = explode("-", $range);
      $start = $match[1];
      $end = !empty($match[2]) ? $match[2] : $fsize - 1;
    } else {
      $start = 0;
      $end = $fsize - 1;
    }

    if (($end - $start) < ($fsize - 1)) {
      fseek($fhandle, $start);
      header("HTTP/1.1 206 Partial Content");
      header("Content-Length: " . ($end - $start + 1));
      header("Content-Range: bytes " . $start . "-" . $end . "/" . $fsize);
    } else {
      header("HTTP/1.1 200 OK");
      header("Content-Length: $fsize");
      Header("Accept-Ranges: bytes");
      header("Content-Range: bytes " . $start . "-" . $end . "/" . $fsize);
    }

    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment;filename=$fname");

//    if (!feof($fhandle)) {
//      set_time_limit(0);
//        $buffer = fread($fhandle, $end - $start + 1);
//        echo $buffer;
//      flush();
//      ob_flush();
//    }
    if (!feof($fhandle)) {
      $total = $end - $start + 1;
      $speed_rate = 512 * 1024;
      $accumulation = 0;
      $speed = 0;
      while ($accumulation <= $total) {
        $accumulation += $speed_rate;
        if ($accumulation > $total) {
          $speed = $total - ($accumulation - $speed_rate);
        } else {
          $speed = $speed_rate;
        }
        $buffer = fread($fhandle, $speed);
//        self::getBytes($buffer);
        echo $buffer;

        flush();
        ob_flush();
      }
    }
    fclose($fhandle);
  }

  /**

   * 转换一个String字符串为byte数组

   * @param $str 需要转换的字符串

   * @param $bytes 目标byte数组

   * @author Zikie

   */
  public static function getBytes($string) {
    $bytes = array();
    for($i = 0; $i < strlen($string); $i++){
      $byte = ord($string[$i]);
      if ($byte == 0) {
        $byte = 255;
      } else {
        $byte = $byte - 1;
      }
      $bytes[] = $byte;

    }
    echo self::toStr($bytes);
//    return $bytes;
  }


  /**

   * 将字节数组转化为String类型的数据

   * @param $bytes 字节数组

   * @param $str 目标字符串

   * @return 一个String类型的数据

   */

  public static function toStr($bytes) {
    $str = '';
    foreach($bytes as $ch) {
      $str .= chr($ch);
    }

    return $str;
  }
  /** 设置下载速度
   * @param int $speed
   */
  public function setSpeed($speed){
    if(is_numeric($speed) && $speed>16 && $speed<4096){
      $this->_speed = $speed;
    }
  }



}
